
import { _decorator, Component, Node, GFXColorAttachment, GFXDepthStencilAttachment,
    RenderTexture, SpriteFrame, Sprite, Camera, UITransform, tween, Vec3, view, Tween, Rect } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CaptureForWeb')
export class CaptureForWeb extends Component {

    @property(Sprite)
    sprite !: Sprite;
    @property(Camera)
    cameraRenderer !: Camera;

    onLoad() {
        this.refreshRenderTexture();
    }

    refreshRenderTexture(): void {
        const _colorAttachment = new GFXColorAttachment();
        const _depthStencilAttachment = new GFXDepthStencilAttachment();

        const _width = this.sprite.node.getComponent(UITransform)!.contentSize.width;
        const _height = this.sprite.node.getComponent(UITransform)!.contentSize.height;

        let renderTex = new RenderTexture();
        renderTex.reset({
            width: _width,
            height: _height,
            passInfo: {
                colorAttachments: [_colorAttachment],
                depthStencilAttachment: _depthStencilAttachment,
                subPasses : []
            }
        });

        let spriteframe: SpriteFrame = this.sprite.spriteFrame!;
        let sp: SpriteFrame = new SpriteFrame();
        sp.reset({
            originalSize: spriteframe.originalSize,
            rect: spriteframe.rect,
            offset: spriteframe.offset,
            isRotate: spriteframe.rotated,
            borderTop: spriteframe.insetTop,
            borderLeft: spriteframe.insetLeft,
            borderBottom: spriteframe.insetBottom,
            borderRight: spriteframe.insetRight,
        });

        this.cameraRenderer.targetTexture = renderTex;
        sp.texture = renderTex;
        this.sprite.spriteFrame = sp;
    }

    onClickCapture (){
        Tween.stopAllByTarget(this.sprite.node);

        const _width = view.getVisibleSize().width;
        const _height = view.getVisibleSize().height;

        this.sprite.node.setPosition(0, 0, 0);
        this.sprite.node.setScale(1, 1, 1);
        tween(this.sprite.node).to(1, {scale: new Vec3(0.3, 0.3, 0.3) } )
            .to(1, { position: new Vec3(_width * 3 / 8,  - _height / 8, 0)})
            .start();
    }
}

